package com.anjubao.parking.municipal.common.aop;

import java.time.LocalDateTime;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.anjubao.parking.municipal.common.entity.BaseEntity;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

/**
 * Entity数据库CRUD事件监听，完成一些公共字段操作
 *
 */
@Component
public class MetaCommonHandler implements MetaObjectHandler {

	@Override
	public void insertFill(MetaObject metaObject) {
		String agent = agent();
		LocalDateTime now = LocalDateTime.now();
		setInsertFieldValByName("createTime", now, metaObject);
		setInsertFieldValByName("updateTime", now, metaObject);
		setInsertFieldValByName("createdBy", agent, metaObject);
		setInsertFieldValByName("updatedBy", agent, metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		String agent = agent();
		LocalDateTime now = LocalDateTime.now();
		setUpdateFieldValByName("updateTime", now, metaObject);
		setUpdateFieldValByName("updatedBy", agent, metaObject);
	}

	private String agent() {
		String userId = null;
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication != null) {
			Object principal = authentication.getPrincipal();

			if (principal != null && principal instanceof UserDetails) {
				userId = ((UserDetails) principal).getUsername();
			} else if (principal != null) {
				userId = principal.toString();
			}
		}
		return userId == null ? "" : userId;
	}

	private void setValue(MetaObject meta, String field, Object value) {
		Object oldValue = meta.getValue(field);
		if (oldValue == null) {
			meta.setValue(field, value);
		}
	}
}
